﻿
using Halcon二次开发.Data.SocketChild数据;
using Halcon二次开发.Model;
using Halcon二次开发.Model.自定义控件;
using Halcon二次开发.Tools;
using Halcon二次开发.View.Socket通信;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Halcon二次开发.Controller.通信
{
    public class SocketControllerChild
    {
        //窗体对象
        private SocketChildForm socketChildForm;
        /// <summary>
        /// 数据地址
        /// </summary>
        private string jsonPath;

        /// <summary>
        /// 从文件中读取blist标志位
        /// </summary>
        bool blistPaper=false;

        public HwindowFlowNodeUrseControl hwindowFlowNode;

        public SocketControllerChild(SocketChildForm socketChildForm)
        {
            this.socketChildForm = socketChildForm;
        }

        public SocketControllerChild(SocketChildForm socketChildForm, string jsonPath, HwindowFlowNodeUrseControl hwindowFlowNode) : this(socketChildForm)
        {
            this.jsonPath = jsonPath;
            this.hwindowFlowNode = hwindowFlowNode;
            if (!Directory.Exists(jsonPath))
            {
                Directory.CreateDirectory(jsonPath);
            }
        }

        public SocketDome Add(BindingList<SocketDome> blist,ref int count, Action<SocketDome> nameChanged)
        {
            if (blist != null)
            {
                SocketDome s = new SocketDome(count, nameChanged);
                blist.Add(s);
                count++;
                return s;
            }
            return null;
        }
        public bool Delete(BindingList<SocketDome> blist,int index)
        {
            if (blist != null)
            {
                blist.RemoveAt(index);
                return true;
            }else
            {
                return false;
            }
        }
        public void  MoveUp(BindingList<SocketDome> blist,int index)
        {
            if (index == 0) return;
            SocketDome s1= blist[index-1];
            blist[index - 1] = blist[index];
            blist[index] = s1;
        }
        public void DownMove(BindingList<SocketDome> blist, int index)
        {
            if (index == blist.Count-1) return;
            SocketDome s1 = blist[index+1];
            blist[index + 1] = blist[index];
            blist[index] = s1;
        }
        public void Run()
        {
            //初始化运行时执行一次
            
            if (!blistPaper)
            {
                GetLists();
                GetNodes();
                Thread flashBlist = new Thread(Flash);// 运行时开始持续刷新数据
                flashBlist.Start();
                flashBlist.IsBackground = true;
                blistPaper = true;
            }
            try
            {
                SocketController sc = SocketController.GetSocketController();
                if (sc.socket != null)
                {
                    foreach (SocketDome item in socketChildForm.blist)
                    {
                        sc.Sends(item.ToString());
                    }
                   
                }
                else
                {
                    throw new Exception("socket未连接!");
                }
            }
            catch(Exception ex)
            {
                if (ex.Message.Contains("socket未连接!"))
                {
                    throw new Exception(ex.Message);
                }else
                {
                    throw new Exception("发送信息错误! 已中断发送");
                }
                
            }
        }
        /// <summary>
        /// 持续根据节点刷星datagridview的数据
        /// </summary>
        private void Flash()
        {
            while (true)
            {
                Thread.Sleep(100);
                foreach (TreeNode cnode in socketChildForm.treeView1.Nodes[0].Nodes)
                {
                    if (cnode.Text.Contains("<—"))
                    {
                        string[] str = cnode.Text.Split(new char[] { '<', '—', '.' }, StringSplitOptions.RemoveEmptyEntries);
                        string formName = str[1].Trim();//窗体对象名
                        string fieldName = str[2].Trim();//字段名

                        TreeView treeView = hwindowFlowNode.treeView1;// 根节点
                        foreach (TreeNode hNode in treeView.Nodes)
                        {
                            if (hNode.Text == formName)// 找到根节点
                            {
                                foreach (TreeNode chNode in hNode.Nodes)
                                {
                                    if (chNode.Text == fieldName)// 找到动作对象
                                    {
                                        object controller = chNode.Tag;
                                        FieldInfo field = controller.GetType().GetField(fieldName);
                                        if (field.Name == "double")
                                        {
                                            MessageBox.Show("111");
                                        }
                                        object value = field.GetValue(controller);//得到字段的值

                                        (cnode.Tag as SocketDome).Result = value;// 赋值
                                    }
                                }
                            }

                        }

                    }
                }
                socketChildForm.uiDataGridView1.Refresh();
            }
        }

        /// <summary>
        /// 获取json数据1 blist数据
        /// </summary>
        /// <param name="path"></param>
        /// <param name="addres"></param>
        public void GetLists()
        {
            string paths = jsonPath + "\\" + this.socketChildForm.Name + ".json";
            //调用读取方法
            List<SocketDome> list = HelpJsons.Read<SocketDome>(paths);

            if (list != null && list.Count > 0)
            {
                foreach (SocketDome item in list)
                {
                    socketChildForm.blist.Add(item);
                    item.nameChanged = socketChildForm.nameChanged;
                    //同步计数器
                    if (item.Name.Contains("Input"))
                    {
                       string i= item.Name.Split(new char[] { 'I', 'n', 'p', 'u', 't' }, StringSplitOptions.RemoveEmptyEntries)[0];
                        int n = int.Parse(i);
                        if (n >=socketChildForm.count)
                        {
                            socketChildForm.count = n+1;
                        }
                    }
                }
            }
       }
        /// <summary>
        /// 获取json数据1 blist数据
        /// </summary>
        /// <param name="path"></param>
        /// <param name="addres"></param>
        public void GetNodes()
        {
            string paths = jsonPath + "\\" + this.socketChildForm.Name + "节点.txt";
            if (!File.Exists(paths)) return;
            //调用读取方法
            string[] strs=  File.ReadAllLines(paths);
            foreach (string item in strs)
            {
                if (item.Contains("<"))
                {

                    string[] s = item.Split(new char[] { '<', '—' },StringSplitOptions.RemoveEmptyEntries);
                    if (socketChildForm.blist == null || socketChildForm.blist.Count == 0) return;
                    SocketDome dome = socketChildForm.blist.First(f => f.Name == s[0]);
                    socketChildForm.AddNode(dome, s[0], item);
                    continue;
                }
                else
                {
                    if (socketChildForm.blist == null || socketChildForm.blist.Count == 0) return;
                    SocketDome dome = socketChildForm.blist.First(f => f.Name ==item);
                    socketChildForm.AddNode(dome, item, item);
                }
            }
        } /// <summary>
          /// 获取json数据1 blist数据
          /// </summary>
          /// <param name="path"></param>
          /// <param name="addres"></param>
        public void SetLists()
        {
            string paths = jsonPath + "\\" + this.socketChildForm.Name + ".json";
            if (!File.Exists(paths))
            {
                using (File.Create(paths)) { }
            }
            List<SocketDome> list = new List<SocketDome>();
           
            if (socketChildForm.blist == null && socketChildForm.blist.Count == 0) return;
            foreach (SocketDome item in socketChildForm.blist)
            {
                list.Add(item);
            }
            //调用写入方法
            HelpJsons.Write<SocketDome>(list, paths);
        }
        /// <summary>
        /// 获取json数据1 blist数据
        /// </summary>
        /// <param name="path"></param>
        /// <param name="addres"></param>
        public void SetNodes()
        {
            string paths = jsonPath + "\\" + this.socketChildForm.Name + "节点.txt";
            if (File.Exists(paths))
            {
                File.Delete(paths);
               
            }
            using (File.Create(paths)) { }
            string[] str = new string[socketChildForm.treeView1.Nodes[0].Nodes.Count];
            for (int i = 0; i < socketChildForm.treeView1.Nodes[0].Nodes.Count; i++)
            {
                str[i]= socketChildForm.treeView1.Nodes[0].Nodes[i].Text;
            }
            //调用读取方法
            File.WriteAllLines(paths,str);
        }
    }
}
